// pages/admin-daily-work-report/admin-daily-work-report.js
const app = getApp()

Page({
  data: {
    records: [],
    loading: true,
    loadingMore: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    
    // 筛选条件
    filterDate: '',
    statusIndex: 0,
    statusOptions: [
      { value: '', text: '全部状态' },
      { value: '0', text: '待审核' },
      { value: '1', text: '通过' },
      { value: '2', text: '拒绝' }
    ],
    userIndex: 0,
    userOptions: [
      { value: '', text: '全部员工' }
    ],
    
    // 统计信息
    stats: {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0
    },
    
    // 审核弹窗
    showAuditModal: false,
    auditForm: {
      id: null,
      status: 1,
      reason: ''
    }
  },

  onLoad() {
    this.loadUsers()
    this.loadRecords()
    this.loadStats()
  },

  onShow() {
    // 刷新数据
    this.setData({
      page: 1,
      records: [],
      hasMore: true
    })
    this.loadRecords()
    this.loadStats()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      records: [],
      hasMore: true
    })
    this.loadRecords().then(() => {
      wx.stopPullDownRefresh()
    })
    this.loadStats()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMore()
    }
  },

  // 加载员工列表
  loadUsers() {
    app.request({
      url: '/getSimpleUserList',
      method: 'GET'
    }).then((res) => {
      if (res.code === 1) {
        const users = res.data.map(user => ({
          value: user.id,
          text: user.name
        }))
        this.setData({
          userOptions: [{ value: '', text: '全部员工' }, ...users]
        })
      }
    }).catch((err) => {
      console.error('加载员工列表失败:', err)
    })
  },

  // 加载工作记录
  loadRecords() {
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      page_size: this.data.pageSize
    }
    
    if (this.data.filterDate) {
      params.work_date = this.data.filterDate
    }
    
    if (this.data.statusOptions[this.data.statusIndex].value) {
      params.status = this.data.statusOptions[this.data.statusIndex].value
    }
    
    if (this.data.userOptions[this.data.userIndex].value) {
      params.user_id = this.data.userOptions[this.data.userIndex].value
    }
    
    return app.request({
      url: '/getDailyWorkRecords',
      method: 'GET',
      data: params
    }).then((res) => {
      this.setData({ loading: false })
      
      if (res.code === 1) {
        const newRecords = res.data.list || []
        const records = this.data.page === 1 ? newRecords : [...this.data.records, ...newRecords]
        
        this.setData({
          records: records,
          hasMore: newRecords.length >= this.data.pageSize
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch((err) => {
      this.setData({ loading: false })
      console.error('加载工作记录失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 加载统计信息
  loadStats() {
    app.request({
      url: '/getDailyWorkStats',
      method: 'GET'
    }).then((res) => {
      if (res.code === 1) {
        this.setData({
          stats: res.data
        })
      }
    }).catch((err) => {
      console.error('加载统计信息失败:', err)
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.loadingMore || !this.data.hasMore) {
      return
    }
    
    this.setData({
      loadingMore: true,
      page: this.data.page + 1
    })
    
    this.loadRecords().then(() => {
      this.setData({ loadingMore: false })
    }).catch(() => {
      this.setData({ 
        loadingMore: false,
        page: this.data.page - 1
      })
    })
  },

  // 日期筛选
  onDateChange(e) {
    this.setData({
      filterDate: e.detail.value,
      page: 1,
      records: [],
      hasMore: true
    })
    this.loadRecords()
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      records: [],
      hasMore: true
    })
    this.loadRecords()
  },

  // 员工筛选
  onUserChange(e) {
    this.setData({
      userIndex: e.detail.value,
      page: 1,
      records: [],
      hasMore: true
    })
    this.loadRecords()
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin-daily-work-detail/admin-daily-work-detail?id=${id}`
    })
  },

  // 审核记录
  auditRecord(e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      showAuditModal: true,
      auditForm: {
        id: id,
        status: 1,
        reason: ''
      }
    })
  },

  // 关闭审核弹窗
  closeAuditModal() {
    this.setData({
      showAuditModal: false,
      auditForm: {
        id: null,
        status: 1,
        reason: ''
      }
    })
  },

  // 审核状态改变
  onAuditStatusChange(e) {
    this.setData({
      'auditForm.status': parseInt(e.detail.value)
    })
  },

  // 审核意见输入
  onAuditReasonInput(e) {
    this.setData({
      'auditForm.reason': e.detail.value
    })
  },

  // 提交审核
  submitAudit() {
    if (!this.data.auditForm.reason.trim()) {
      wx.showToast({
        title: '请输入审核意见',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '审核中...'
    })

    app.request({
      url: '/auditDailyWorkReport',
      method: 'POST',
      data: {
        id: this.data.auditForm.id,
        status: this.data.auditForm.status,
        audit_reason: this.data.auditForm.reason
      }
    }).then((res) => {
      wx.hideLoading()
      
      if (res.code === 1) {
        wx.showToast({
          title: '审核成功',
          icon: 'success'
        })
        
        this.closeAuditModal()
        this.loadRecords()
        this.loadStats()
      } else {
        wx.showToast({
          title: res.msg || '审核失败',
          icon: 'none'
        })
      }
    }).catch((err) => {
      wx.hideLoading()
      console.error('审核失败:', err)
      wx.showToast({
        title: '审核失败',
        icon: 'none'
      })
    })
  }
})
